﻿using Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Filters
{
    /// <summary>
    /// 操作记录特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class ActionLogAttribute : FilterAttribute, IActionFilter
    {
        /// <summary>
        /// 操作名
        /// </summary>
        public string ActionName { get; set; }
        /// <summary>
        /// 操作记录特性
        /// </summary>
        /// <param name="actionName">操作名</param>
        public ActionLogAttribute(string actionName)
        {
            this.ActionName = actionName;
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }

        /// <summary>
        /// Action执行完成之后
        /// </summary>
        /// <param name="filterContext">上下文对象</param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var controller = filterContext.Controller as BasicController;
            if (controller == null || controller.LoginUser == null)
            {
                return;
            }
            var log = new SystemLog { ActionTime = DateTime.Now, Action = this.ActionName, UserId = controller.LoginUser.ID };
            controller.DbContext.SystemLog.Add(log);
            controller.DbContext.SaveChanges();
        }
    }
}